<?php

namespace app\open\service;

use app\admin\model\Shop;
use app\common\model\Business;
use app\common\model\BusinessWalletLog;
use app\admin\model\Play;
use think\Db;
use think\Exception;

/**
 * 活动
 * Class PlayService
 * @package app\api\service
 */
class PlayService extends BaseService
{
    public function getPlayList($where, $lat, $lng, $order = "distance asc,id desc", $page = 1,$high_rebate,$snatchable, $pageSize = 10, $extend = [], $is_collection=0)
    {
        if (!isset($where['g.play_type'])) {
            $where['g.play_type'] = ['in',[1,3]];
        }
        $nowDateTime = time();
        $nowTime = $nowDateTime - strtotime(date("Y-m-d 00:00:00", $nowDateTime));
        // $field = "g.*,s.logo_pic,s.id as s_id,s.shop_name as s_name,s.shop_type as s_type,s.phone,s.lat,s.lng,s.address,s.shop_status as s_status,round((6378.138 * 2 * asin(sqrt(pow(sin((s.lat * pi() / 180 - " . $lat . " * pi() / 180) / 2),2) + cos(s.lat * pi() / 180) * cos(" . $lat . " * pi() / 180) * pow(sin((s.lng * pi() / 180 - " . $lng . " * pi() / 180) / 2),2))) * 1000)/1,1) as distance";
        $field = "g.*,s.id as s_id,s.logo_pic,s.shop_name as s_name,s.shop_type as s_type,s.phone,s.lat,s.lng,s.address,s.shop_status as s_status,10000*(abs(s.lng-".$lng.")+abs(s.lat -".$lat.")) as distance,s.dpzxelm,pc.quota";
        $map = [
            'g.play_status' => ['=', 2],
            'g.start_date' => ['<=', $nowDateTime],
            'g.end_date' => ['>=', $nowDateTime],
            's.shop_status' => ['=', '1'],
        ];
        $map = array_merge($map, $where);
        $db2 = Db::connect(config('database.db2'));
        $list = $db2->name('play')->alias('g')
            ->join('chbc_shop s', "g.shop_no=s.shop_no")
            ->join('chbc_play_channel pc','pc.play_id=g.id')
            ->field($field)
            ->where($map)
            ->order($order)
            ->group('g.shop_no')
            ->page($page, $pageSize)
            ->select();
        $playObj = (new Play());
        $shopObj = (new Shop());
        $data = [];
        $shop_type = [1=>'mt',2=>'ele',3=>'jd'];
        foreach ($list as $k => $v) {
            $data[$k]['storeId'] = $v['s_id'];
            $data[$k]['platformCode'] = $shop_type[$v['s_type']];
            $data[$k]['cover'] = $playObj->getImgUrlAttr('',$v);
            $distance = $this->get_distance([$lat,$lng],[$v['lat'],$v['lng']]);
            $data[$k]['distance'] = round($distance/1000,2).'km';
            $data[$k]['name'] = $v['s_name'];
            $data[$k]['longitude'] = $v['lng'];
            $data[$k]['latitude'] = $v['lat'];
            $taskList = [];
            $map2 = $map;
            $map2['g.shop_no'] = $v['shop_no'];
            $mutile = $db2->name('play')->alias('g')
                ->join('chbc_shop s', "g.shop_no=s.shop_no")->join('chbc_play_channel pc','pc.play_id=g.id')->field($field)->where($map2)->select();
            foreach ($mutile as $key => $value) {
                $taskList[$key]['id'] = $value['id'];
                $taskList[$key]['storeId'] = $v['s_id'];
                $taskList[$key]['mealPrice'] = floatval($value['user_pay']);
                $taskList[$key]['settlementAmount'] = round($value['shop_settlement']-$value['service_amt'],2);
                $taskList[$key]['startTime'] = $value['start_time_str'];
                $taskList[$key]['endTime'] = $value['end_time_str'];
                $taskList[$key]['remainingQuota'] = $value['chbcconsume'];
                $taskList[$key]['isPraise'] = $value['scheme_no']==3?0:1;
                $taskList[$key]['activeStatus'] = 0;
                $start_time_str = strtotime(date('Ymd').' '.$value['start_time_str']);
                $end_time_str = strtotime(date('Ymd').' '.$value['end_time_str']);
                $mutile[$key]['seize_order_status'] = '';
                if ($nowDateTime>$end_time_str) {
                    $taskList[$key]['activeStatus'] = 2;
                } elseif ($value['quota']==0) {
                    $taskList[$key]['activeStatus'] = -1;
                } elseif ($end_time_str>$nowDateTime && $start_time_str>$nowDateTime) {
                    $taskList[$key]['activeStatus'] = 0;
                } elseif ($end_time_str>=$nowDateTime && $nowDateTime>=$start_time_str) {
                    $taskList[$key]['activeStatus'] = 1;
                }
            }
            $data[$k]['taskList'] = $taskList;
        }
        $count = $db2->name('play')->alias('g')
        ->join('chbc_shop s', "g.shop_no=s.shop_no")
        ->join('chbc_play_channel pc','pc.play_id=g.id')
        ->field($field)
        ->where($map)
        ->group('g.shop_no')
        ->count();
        $lastPage = $count / $pageSize >= (int)$count / $pageSize ? (int)($count / $pageSize) + 1 : (int)($count / $pageSize);
        if (!$data) $data = [];
        if (!$lastPage) $lastPage = 0;
        if (!$count) $count = 0;
        return $data;
    }

    public function getPlayDetail($id = 0,$lat,$lng)
    {
        $playObj = new Play();
        $db2 = Db::connect(config('database.db2'));
        $play = $db2->name('play')->alias('p')->join('chbc_shop s','s.shop_no=p.shop_no')->field("p.*,s.id as shop_id,s.phone,s.lat,s.lng,s.address,s.logo_pic,sp.qrcode_pic,sp.platform_no,sp.is_xls,sp.elm_appenter,sp.sku as skuList,s.dpzxelm,s.is_sjzp,s.province,s.city,s.area,s.has_qrcode,s.shop_name as sshop_name")->join('chbc_shop_platform sp','sp.shop_no=s.shop_no')->where('p.id', $id)
            ->find();
        $data = [];
        if ($play) {
            // $play = $play->toArray();
            $data['id'] = $play['id'];
            // $data['isPraise'] = $play['scheme_no']==3?0:1;
            $data['storeId'] = $play['shop_id'];
            $data['name'] = $play['sshop_name'];
            $play['img_url'] = $playObj->getImgUrlAttr('',$play);
            $data['cover'] = $play['img_url'];
            $data['mealPrice'] = floatval($play['user_pay']);
            $data['startTime'] = $play['start_time_str'];
            $data['endTime'] = $play['end_time_str'];
            $data['remind'] = $play['remarks'];
            $data['remainingQuota'] = $play['chbcconsume'];
            $data['address'] = $play['address'];
            $data['longitude'] = $play['lng'];
            $data['latitude'] = $play['lat'];
            $distance = $this->get_distance([$lat,$lng],[$play['lat'],$play['lng']]);
            $data['distance'] = round($distance/1000,2).'km';
            $data['settlementAmount'] = round($play['shop_settlement']-$play['service_amt'],2);
            $data['praiseType'] = $play['scheme_no']-1;
            $data['praiseName'] = $playObj->getSchemeNoTextAttr('',$play);
            $data['repurchaseInterval'] = 0;
            $data['appletJumpInfo'] = $this->getAppletJumpInfo($play);
        }
        return $data;
    }

    /**
     * [shopDistance description]
     * @param  [type]  $data type=1,计算列表，type==2，计算单个距离
     * @param  [type]  $lng  [description]
     * @param  [type]  $lat  [description]
     * @param  integer $type [description]
     * @return [type]        [description]
     */
    public static function shopDistance($data,$lng,$lat,$type=1)
    {
        $distance_arr = [];
        if ($type==1) {
            $list = $data;
        } else {
            $list = [$data];
        }
            $txmapurlbase = 'https://apis.map.qq.com/ws/distance/v1/matrix/?mode=bicycling&key='.config('txmap_key').'&from='.$lat.','.$lng;
            if (count($list)>0) {
                $to = '';
                foreach ($list as $lk => $lv) {
                    $to .= $lv['lat'].','.$lv['lng'].';';
                }
                $to = trim($to,';');
                if ($to) {
                    $txmapurl = $txmapurlbase.'&to='.$to;
                    $res = file_get_contents($txmapurl);
                    $decode = json_decode($res,1);
                    if ($decode['status']==0) {
                        foreach ($decode['result']['rows'][0]['elements'] as $dk => $dv) {
                            $distance_arr[] = $dv['distance'] > 1000 ? numberFormat($dv['distance'] / 1000) . "km" : $dv['distance'] . "m";
                        }
                    }
                }
            }
        // } else {
        //     $txmapurl = 'https://apis.map.qq.com/ws/direction/v1/bicycling/?key='.config('txmap_key').'&from='.$lat.','.$lng.'&to='.$data['lat'].','.$data['lng'];
        //     $res = file_get_contents($txmapurl);
        //     var_dump($res);exit;
        //     $decode = json_decode($res,1);
        //     if ($decode['status']==0) {
        //         $distance = $decode['result']['routes'][0]['distance'];
        //         $distance_arr[] = $distance > 1000 ? numberFormat($distance / 1000) . "km" : $distance . "m";
        //     }
        // }
        return $distance_arr;
    }
    public static function get_distance($from,$to,$decimal=2){  
        sort($from);  
        sort($to); 
        $EARTH_RADIUS = 6378.138; // 地球半径系数  
        
        $distance = $EARTH_RADIUS*2*asin(sqrt(pow(sin( ($from[0]*pi()/180-$to[0]*pi()/180)/2),2)+cos($from[0]*pi()/180)*cos($to[0]*pi()/180)* pow(sin( ($from[1]*pi()/180-$to[1]*pi()/180)/2),2)))*1000;  
        return round($distance, $decimal);  
        // $distance_arr = [];
        // $txmapurl = 'https://apis.map.qq.com/ws/distance/v1/matrix/?mode=bicycling&key='.config('txmap_key').'&from='.$from[0].','.$from[1].'&to='.$to[0].','.$to[1];
        // $res = file_get_contents($txmapurl);
        // $decode = json_decode($res,1);
        // if ($decode['status']==0) {
        //     foreach ($decode['result']['rows'][0]['elements'] as $dk => $dv) {
        //         $distance_arr[] = $dv['distance'];
        //     }
        // }
        // return $distance_arr[0];
    } 

    // 签名
    public static function sign($param,$clientSecret)
    {
        ksort($param);
        $md5str = '';
        foreach ($param as $key => $value) {
            if(!is_array($value) && "@" != substr($value, 0, 1))
            {
                $md5str .= $key.$value;
            }
        }
        // $sign = hash_hmac('md5', $md5str, self::clientSecret);
        $sign = strtoupper(md5($clientSecret.$md5str.$clientSecret));
        return $sign;
    }


    // 手机号解密
    public static function aes_decrypt($encrypted, $key, $iv) 
    {   
        $encrypted = base64_decode($encrypted); // 返回 Base64 编码结果  
        $decrypted = openssl_decrypt($encrypted, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
        if ($decrypted === false) {
            return false;
        }
        // 输出解密后的数据（可能需要转换为字符串，如果原始数据是二进制的话）
        return $decrypted;
    }



    public static function point2address($lat,$lng)
    {
        $config = get_addon_config('address');
        $maptype = $config['maptype'];
        if (!isset($config[$maptype . 'key']) || !$config[$maptype . 'key']) {
            return false;
        }
        $res = file_get_contents("https://apis.map.qq.com/ws/geocoder/v1/?location=".$lat.",".$lng."&output=json&key=".$config[$maptype . 'key']);
        $decode = json_decode($res,1);
        if (isset($decode['status']) && $decode['status']==0) {
            return $decode['result'];
        }
        return false;
    }


    public static function elmstoreId($elm_appenter)
    {
        if (strpos($elm_appenter,'https://kong.eleme.cn/h5/')===false) return ['status'=>0,'msg'=>'参数格式不正确'];
        $cachename = str_replace('https://kong.eleme.cn/h5/', '', $elm_appenter);
        $id = \think\Cache::store('redis')->get($cachename);
        if ($id) return ['status'=>1,'data'=>$id];
        $info = '';
        $ch = curl_init($elm_appenter);
        curl_setopt_array($ch, [
            CURLOPT_FOLLOWLOCATION => false,   // 自动跟随 301/302
            CURLOPT_RETURNTRANSFER => true,   // 不输出内容
            CURLOPT_HEADER         => array('Accept:*/*','User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0','Connection: Keep-Alive'),  // 不需要头信息
            CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT        => 5,
        ]);
        curl_setopt($ch, CURLOPT_HEADERFUNCTION,
            function($curl, $headerLine) use (&$header) {
                $header .= $headerLine;
                return strlen($headerLine);
            }
        );
        $res = curl_exec($ch);
        if (!curl_errno($ch)) {
            $info = curl_getinfo($ch);
        }
        curl_close($ch);
        if ($header) {
            $arr = explode('#id=', $header);
            if (!isset($arr[1])) return ['status'=>0,'msg'=>'解析结果有误'];
            $arr = explode('&', $arr[1]);
            if (!isset($arr[1])) return ['status'=>0,'msg'=>'解析结果有误'];
            $id = $arr[0];
            \think\Cache::store('redis')->set($cachename,$id,43200);
            return ['status'=>1,'data'=>$id];
        }
        return ['status'=>0,'msg'=>'解析失败'];
        
    }



    public static function getAppletJumpInfo($play)
    {
        $data = [];
        if ($play['shop_type']==1) {
            if ($play['is_xls']==0) {
                $data['appId'] = 'wx2c348cf579062e56';
                $data['appSourceId'] = 'gh_72a4eb2d4324';
                $data['path'] = 'packages/restaurant/restaurant/restaurant?aas=1003&cat_id=0&poi_id='.$play['platform_no'];
                $data['shortLink'] = '';
            } else {
                $data['appId'] = 'wxc341b03f979e49ad';
                $data['appSourceId'] = 'gh_3d18695c9521';
                $data['path'] = '?extra=%7B%22recommend_top_skus%22%3A%5B30196314789%2C25301356262%2C25303720621%2C30198410469%5D%2C%22second_kingkong_code%22%3A101585%2C%22first_kingkong_code%22%3A101578%7D&__preload__=1741702641722&g_source=sg_1383&poi_id=-100&poi_id_str='.$play['platform_no'];
                $data['shortLink'] = '';
            }
        } elseif ($play['shop_type']==2) {
            if ($play['is_xls']==0) {
                if ($play['elm_appenter']) {
                    $elmstoreid = self::elmstoreId($play['elm_appenter']);
                    if ($elmstoreid['status']) {
                        $play['platform_no'] = $elmstoreid['data'];
                    }
                }
                $data['appId'] = 'wxece3a9a4c82f58c9';
                $data['appSourceId'] = 'gh_6506303a12bb';
                $data['path'] = 'ele-estore/ele-takeout-index/ele-takeout-index?shopId='.$play['platform_no'];
                $data['shortLink'] = '';
            } else {
                $data['appId'] = 'wx9d8146a861813ecc';
                $data['appSourceId'] = 'gh_2778036e1860';
                $data['path'] = 'pages/container/index.html?q=https://h5-newretail.faas.ele.me/static/h5_newretail/pages/shop.html?isTransfer=1&from=eb_qrcode*from=seller_domain.shop_setup.shop_qrcode_share&id=510335697&geolat=31.265196&*geolng=121.478534&geolng=121.478534&*geolat=31.265196&store_id='.$play['platform_no'];
                $data['shortLink'] = '';
            }
        } else {
            parse_str($play['platform_no'],$output);
            $appId = '';
            $storeId = '';
            $venderId = '';
            if (isset($output['appId'])) $appId = $output['appId'];
            if (isset($output['storeId'])) $storeId = $output['storeId'];
            if (isset($output['venderId'])) $venderId = $output['venderId'];
            if ($appId) {
                $play['elm_appenter'] = sprintf(config('jd_appenter'),$appId,$storeId,$venderId);
            } else {
                $play['elm_appenter'] = '';
            }
            $data['appId'] = 'wx91d27dbf599dff74';
            $data['appSourceId'] = 'gh_45b306365c3d';
            $data['path'] = $play['elm_appenter'];
            $data['shortLink'] = '';
        }
        return $data;
    }
}